import { computed, ref } from 'vue'

export default function useShortcut (props, groupRef) {
  const scrollRef = ref(null)
  // 保存手指滑动初始值和结束值，计算偏移量
  const touch = {}

  const shortcutList = computed(() => {
    return props.data.map((item) => {
      return item.title
    })
  })

  function onShortcutTouchStart (e) {
    // 第一个手指touch时的Y
    touch.y1 = e.touches[0].pageY
    // 获取到目标组索引
    const targetIndex = Number(e.target.dataset.index)
    touch.targetIndex = targetIndex
    // 获取到目标组的dom li
    const targetEl = groupRef.value.children[targetIndex]
    // 获取scroll对象实例, 暂时不知道为什么这样获取
    const scroll = scrollRef.value.scroll.scroll._value
    // console.log(scroll)
    // scroll实例的API,滚动到对应位置，滚动时间为0
    scroll.scrollToElement(targetEl, 0)
    // console.log(scroll)
  }

  function onShortcutTouchMove (e) {
    touch.y2 = e.touches[0].pageY
    // 计算偏移量,经过了几个shortcut的li，每个字母的高度18px
    const delta = Math.floor((touch.y2 - touch.y1) / 18)
    let targetIndex = touch.targetIndex + delta
    // 限制targetIndex防止越界
    targetIndex = Math.max(0, Math.min(targetIndex, shortcutList.value.length - 1))
    const targetEl = groupRef.value.children[targetIndex]
    const scroll = scrollRef.value.scroll.scroll._value
    // console.log(scroll)
    // scroll实例的API,滚动到对应位置，滚动时间为0
    scroll.scrollToElement(targetEl, 0)
  }

  return { shortcutList, onShortcutTouchStart, onShortcutTouchMove, scrollRef }
}
